package com.yl.core.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Todo
 *
 * @Author jiangtao
 * @CreateBy 2019-07-05 1:50 PM
 * @UpdateBy jiangtao
 * @Version v1.0
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    //不需要拦截的链接
    private static List<String> allowUrls;
    static {
        allowUrls = new ArrayList<>();
        allowUrls.add("/login");
        allowUrls.add("/quickLogin");
        allowUrls.add("/register");
        allowUrls.add("/logout");
        allowUrls.add("/captcha");

    }

    /**
     * This implementation always returns {@code true}.
     * @param request
     * @param response
     * @param handler
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        HttpSession session = request.getSession();

        /*
        String uri = request.getRequestURI();

        //其他URI，一般处理，不需要拦截的URL
        for (String str : allowUrls) {
            if (uri.indexOf(str) >= 0) {
                return true;
            }
        }*/

        String username = (String) session.getAttribute("username");
        //已登录通过验证，放行
        if (StringUtils.isEmpty(username)) {
            //普通请求回到登录页面
            request.setAttribute("message", "您还没有登录，或页面已过期，请先登录！");
            request.getRequestDispatcher("/expire").forward(request, response);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
